var Promise = require('promise');
var ui_pub_sub = require('./ui_pub_sub_collection').ui_pub_sub;

var Insert = function(topic, data) {

	return new Promise((resolve, reject) => {
		var client = new ui_pub_sub();
		client.topic = topic;
		client.data = data;
		client.timestamp = new Date().getTime();
		var callback = function(err) {
			if(err) {
				var msg = 'Save topic:' + topic + ', failed';
				return reject(err, msg);
			} else {
				var msg = 'Save topic:' + topic + ', success';
				return resolve(msg);
			}
		}
		client.save(callback);
	});
}

var QueryDataLimit = function(topic, limit) {
	return new Promise((resolve, reject) => {
		var _userid = {topic: topic};
		var callback = function(err, datas) {
			if(err) {
				var msg = 'QueryDataLimit topic:' + topic + ' failed';
				return reject(err, msg);
			} else {
				return resolve(datas);
			}
		}
		new ui_pub_sub({}).QueryDataLimit(_userid, limit, callback);
	});
}

var QueryDataBetweenTimeLimit = function(topic, begintime, endtime, limit) {
	return new Promise((resolve, reject) => {
		var _userid = {topic: topic};
		var callback = function(err, datas) {
			if(err) {
				var msg = 'QueryDataBetweenTimeLimit topic:' + topic + ' failed';
				return reject(err, msg);
			} else {
				return resolve(datas);
			}
		}
		new ui_pub_sub({}).QueryDataBetweenTimeLimit(_userid, begintime, endtime, limit, callback);
	});
}


exports.Insert = Insert;
exports.QueryDataLimit = QueryDataLimit;
exports.QueryDataBetweenTimeLimit = QueryDataBetweenTimeLimit;

